<script setup>
import { reactive, ref, defineEmits } from 'vue';
import { ElNotification } from 'element-plus';

const emits = defineEmits(['sendSearchOptions']);

const option = reactive({
  query: '',
  searchType: '',
});

const isComposing = ref(false); // 标记是否在输入法组合过程中

const handleCompositionStart = () => {
  isComposing.value = true;
};

const handleCompositionEnd = () => {
  isComposing.value = false;
  handleQueryChange(); // 输入法组合结束后手动触发一次判断
};

const handleQueryChange = () => {
  if (isComposing.value) return; // 输入法组合期间不处理

  // 判断是否为纯数字
  if (/^[Ee]\d+$/.test(option.query)) {
    option.searchType = 'idCard';
  } else {
    option.searchType = 'name';
  }
};

const handleSearch = async () => {
  // 清空查询条件时，触发查询所有数据
  if (!option.query.trim()) {
    // 传递空查询条件
    emits('sendSearchOptions', { query: '', searchType: '' });
    ElNotification({
      title: '提示',
      message: '未输入查询条件，将查询所有数据。',
      type: 'info',
    });
  } else {
    // 查询时传递当前条件
    emits('sendSearchOptions', option);
  }
};

const handleReset = () => {
  // 清空查询条件
  option.query = '';
  option.searchType = '';
  // 触发父组件重置数据
  emits('sendSearchOptions', { query: '', searchType: '' });
};
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="option.query"
      placeholder="请输入姓名或身份证号码"
      @input="handleQueryChange"
      @compositionstart="handleCompositionStart"
      @compositionend="handleCompositionEnd"
      class="search-input"
    />
    <el-button type="primary" @click="handleSearch" class="search-button"
      >查询</el-button
    >
    <el-button @click="handleReset" class="reset-button">重置</el-button>
  </div>
</template>

<style scoped>
.search-container {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 修改为右对齐 */
  gap: 10px;
  padding-top: 1px;
  padding-bottom: 5px;
}

.search-input {
  width: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
  font-size: 14px;
}

.search-button,
.reset-button {
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  font-size: 14px;
}

.search-button {
  background-color: #409eff;
  color: white;
}

.reset-button {
  background-color: #f4f4f4;
  color: #409eff;
  border: 1px solid #409eff;
}

.search-button:hover,
.reset-button:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.search-button:active,
.reset-button:active {
  transform: scale(0.98);
}

.reset-button:hover {
  background-color: #e6f7ff;
}

.search-input .el-input__inner {
  font-size: 14px;
}
</style>
